package com.example.ai.service;

import com.example.ai.dto.wrongquestion.ReviewNoteRequest;
import com.example.ai.dto.wrongquestion.WrongQuestionRequest;
import com.example.ai.dto.wrongquestion.WrongQuestionResponse;
import com.example.ai.exception.ResourceNotFoundException;
import com.example.ai.model.Question;
import com.example.ai.model.User;
import com.example.ai.model.WrongQuestion;
import com.example.ai.repository.AnswerRepository;
import com.example.ai.repository.QuestionRepository;
import com.example.ai.repository.UserRepository;
import com.example.ai.repository.WrongQuestionRepository;
import com.example.ai.dto.review.ReviewHistoryResponse;
import com.example.ai.model.ReviewHistory;
import com.example.ai.repository.ReviewHistoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.ai.exception.BusinessException;

import java.time.LocalDateTime;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class WrongQuestionService {

    private final WrongQuestionRepository wrongQuestionRepository;
    private final QuestionRepository questionRepository;
    private final AnswerRepository answerRepository;
    private final UserRepository userRepository;
    private final ReviewHistoryRepository reviewHistoryRepository;

    @Transactional
    public WrongQuestionResponse addToWrongQuestion(String username, WrongQuestionRequest request) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new BusinessException("用户不存在"));

        // 检查是否已存在相同的问题
        Optional<WrongQuestion> existingQuestion = wrongQuestionRepository
                .findByUserIdAndQuestionId(user.getId(), request.getQuestionId());

        if (existingQuestion.isPresent()) {
            throw new BusinessException("该问题已添加到备忘录中");
        }

        // 创建新记录
        WrongQuestion wrongQuestion = new WrongQuestion();
        wrongQuestion.setUser(user);
        wrongQuestion.setQuestionId(request.getQuestionId());
        wrongQuestion.setUserAnswer(request.getUserAnswer());
        wrongQuestion.setCorrectAnswer(request.getCorrectAnswer());
        wrongQuestion.setAnalysis(request.getAnalysis());

        wrongQuestion = wrongQuestionRepository.save(wrongQuestion);
        return convertToResponse(wrongQuestion);
    }

    @Transactional(readOnly = false)
    public Page<WrongQuestionResponse> getWrongQuestions(String username, Pageable pageable) {
        return wrongQuestionRepository.findByUserUsername(username, pageable)
                .map(this::convertToResponse);
    }

    @Transactional
    public WrongQuestionResponse updateWrongQuestion(Long id, WrongQuestionRequest request) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new ResourceNotFoundException("User not found"));

        WrongQuestion wrongQuestion = wrongQuestionRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Wrong question not found"));

        // 确保只能更新自己的错题
        if (!wrongQuestion.getUser().getId().equals(user.getId())) {
            throw new IllegalStateException("Not authorized to update this wrong question");
        }

        wrongQuestion.setUserAnswer(request.getUserAnswer());
        wrongQuestion.setCorrectAnswer(request.getCorrectAnswer());
        wrongQuestion.setAnalysis(request.getAnalysis());
        wrongQuestion.setUpdatedAt(LocalDateTime.now());

        return convertToResponse(wrongQuestion);
    }

    @Transactional
    public void deleteWrongQuestion(Long id) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new ResourceNotFoundException("User not found"));

        WrongQuestion wrongQuestion = wrongQuestionRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Wrong question not found"));

        if (!wrongQuestion.getUser().getId().equals(user.getId())) {
            throw new IllegalStateException("Not authorized to delete this wrong question");
        }

        wrongQuestionRepository.delete(wrongQuestion);
    }

    @Transactional
    public WrongQuestionResponse addReviewNote(ReviewNoteRequest request) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("User not found"));

        WrongQuestion wrongQuestion = wrongQuestionRepository.findById(request.getWrongQuestionId())
                .orElseThrow(() -> new RuntimeException("Wrong question not found"));

        if (!wrongQuestion.getUser().getId().equals(user.getId())) {
            throw new RuntimeException("Not authorized to update this wrong question");
        }

        // 保存回顾历史
        ReviewHistory reviewHistory = new ReviewHistory();
        reviewHistory.setWrongQuestion(wrongQuestion);
        reviewHistory.setReviewNote(request.getReviewNote());
        reviewHistoryRepository.save(reviewHistory);

        // 更新错题的回顾信息
        wrongQuestion.setReviewNote(request.getReviewNote());
        wrongQuestion.setReviewCount(wrongQuestion.getReviewCount() + 1);
        wrongQuestion.setLastReviewTime(LocalDateTime.now());

        wrongQuestion = wrongQuestionRepository.save(wrongQuestion);
        return convertToResponse(wrongQuestion);
    }

    @Transactional(readOnly = false)
    public Page<ReviewHistoryResponse> getReviewHistory(Long wrongQuestionId, Pageable pageable) {
        return reviewHistoryRepository.findByWrongQuestionIdOrderByCreatedAtDesc(wrongQuestionId, pageable)
                .map(this::convertToReviewHistoryResponse);
    }

    private WrongQuestionResponse convertToResponse(WrongQuestion wrongQuestion) {
        WrongQuestionResponse response = new WrongQuestionResponse();
        response.setId(wrongQuestion.getId());
        response.setQuestionId(wrongQuestion.getQuestionId());
        response.setUserAnswer(wrongQuestion.getUserAnswer());
        response.setCorrectAnswer(wrongQuestion.getCorrectAnswer());
        response.setAnalysis(wrongQuestion.getAnalysis());
        response.setReviewNote(wrongQuestion.getReviewNote());
        response.setReviewCount(wrongQuestion.getReviewCount());
        response.setLastReviewTime(wrongQuestion.getLastReviewTime());
        response.setCreatedAt(wrongQuestion.getCreatedAt());
        response.setUpdatedAt(wrongQuestion.getUpdatedAt());
        return response;
    }

    private ReviewHistoryResponse convertToReviewHistoryResponse(ReviewHistory history) {
        ReviewHistoryResponse response = new ReviewHistoryResponse();
        response.setId(history.getId());
        response.setReviewNote(history.getReviewNote());
        response.setCreatedAt(history.getCreatedAt());
        return response;
    }
} 